package com.llg.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.llg.mapper.ReceiveBrandMapper;
import com.llg.model.code.CommonCode;
import com.llg.model.code.PageCode;
import com.llg.model.response.*;
import com.llg.pojo.ReceiveBrand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;


@Service
public class ReceiveBrandService {
    @Autowired
    private ReceiveBrandMapper receiveBrandMapper;

    //查找全部接收卡品牌
    public PageResult<ReceiveBrand> findAll() {
        return new PageResult<>(CommonCode.SUCCESS, 1,1, receiveBrandMapper.selectAll());
    }

    //搜索并分页查询
    public PageResult<ReceiveBrand> findList(int currentPage, int pageSize, ReceiveBrand receiveBrand) {
        //判断参数是否合法
        if (currentPage <= 0) return new PageResult<>(PageCode.PAGE_ERR1, 0, 0, null);
        if (pageSize <= 0) return new PageResult<>(PageCode.SIZE_ERR, 0, 0, null);
        PageHelper.startPage(currentPage, pageSize);
        Example example = new Example(receiveBrand.getClass());
        Example.Criteria criteria = example.createCriteria();
        if (receiveBrand != null) {
            if (receiveBrand.getName() != null && !receiveBrand.getName().equals("")) {
                criteria.andLike("name", "%" + receiveBrand.getName() + "%");
            }
        }
        List<ReceiveBrand> receiveBrands = receiveBrandMapper.selectByExample(example);
        PageInfo<ReceiveBrand> page = new PageInfo<>(receiveBrands);
        return new PageResult<>(CommonCode.SUCCESS, (int) page.getTotal(),page.getPageNum(), page.getList());
    }

    //通过id查找
    public DataResult<ReceiveBrand> findById(int id) {
        return new DataResult<>(CommonCode.SUCCESS, receiveBrandMapper.selectByPrimaryKey(id));
    }

    //增
    public DataResult<ReceiveBrand> add(ReceiveBrand receiveBrand) {
        receiveBrandMapper.insertSelective(receiveBrand);
        return new DataResult<>(CommonCode.SUCCESS, receiveBrand);
    }

    //删
    public ResponseResult delete(int id) {
        receiveBrandMapper.deleteByPrimaryKey(id);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    //改
    public ResponseResult update(ReceiveBrand receiveBrand) {
        receiveBrandMapper.updateByPrimaryKeySelective(receiveBrand);
        return new ResponseResult(CommonCode.SUCCESS);
    }

}